<style lang="scss" scoped>
  /*定义元素最终移动到的位置，以及移动到此位置需要的时间*/
  .slide-enter-active{
    transition: all .5s ease;
    -webkit-transition: all .5s ease;
    transform:translate3d(0,0,0);
    -webkit-transform:translate3d(0,0,0)
  }

  /*定义元素从什么位置离开，以及离开岛指定位置所需的时间*/
  .slide-leave-active{
    transition: all .5s ease;
    -webkit-transition: all .5s ease;
    transform:translate3d(0,0,0);
    -webkit-transform:translate3d(0,0,0)
  }
  /*定义元素从100%的位置移入到0，过渡结束后再从0回到100%的位置*/
  .slide-enter,.slide-leave-to{
    transform:translate3d(100%,0,0);
    -webkit-transform:translate3d(100%,0,0)
  }
  .map-box{
    height: 100%;
    position: relative;
    .jiejing{
      bottom: 3px;
      width: 50%;
      background: #f7f8fa;
      position: absolute;
      top: 0;
      right: 0;
      z-index: 10000;
    }
  }
  #panorama {
    width:100%; height: 100%;
  }
  .nojiejing{
    width:100%; height: 100%;
    img{
      margin-top: 20%;
      width: 60%;
      margin-left: 20%;
    }
  }
  .close{
    position: absolute;
    top: 10px;
    right: 10px;
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    background: rgba(255,255,255,.5);
    border: 1px solid #ccc;
    border-radius: 50%;
  }
  .countDevice{
    position: absolute;
    top:60px;
    left: 100px;
    font-size: 14px;
    .name{
      margin-left: 10px;
      margin-right: 10px;
    }
  }
  .countDevice-list{
    padding: 2px 0;
    cursor: pointer;
  }
  .countDevice-list:hover{
    color:#409EFF
  }
  .red{
    color:#fff;
    background-color: red;
  }
  .maploading{
    position: absolute;
    top: 30%;
    left: 50%;
    cursor: pointer;
    width: 220px;
    height: 60px;
    background: #fff;
    text-align: center;
    line-height: 60px;
    margin-left: -110px;
    border-radius: 5px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
    color: #666;
  }
</style>
<template>
  <div class="map-box" v-loading.body="listLoading" element-loading-text="Loading">
    <mainmap v-on:initmap="initmap"></mainmap>
    <transition name="slide">
      <div class="jiejing"  v-show="isShow">
        <div id="panorama" v-show="isJiejing"></div>
        <div class="nojiejing" v-show="!isJiejing">
          <img src="../../assets/no_jiejing.png">
        </div>
        <div class="close" @click="closeJiejing">
          <i class="el-icon-close"></i>
        </div>
      </div>
    </transition>
    <el-popover ref="popover" placement="bottom"  width="600" trigger="click" >
      <el-form :inline="true" >
        <el-form-item >
          <el-input
            placeholder="搜索车牌号、设备ID、使用人、手机号、IMEI号、通信卡号码"
            v-model="seach" style="width: 450px">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="change">查询</el-button>
        </el-form-item>
      </el-form>
    </el-popover>
    <div class="mapOptionBtn">
      <el-button class="countinfo red" @click="openwarning" v-if="ishowredwarning">报警</el-button>
      <el-button class="countinfo" @click="refresh">刷新</el-button>
      <el-button class="countinfo" @click="all">全部</el-button>
      <el-button class="countinfo" v-popover:popover>查询</el-button>
    </div>
    <div class="maploading" v-if="maploading"><i class="el-icon-loading" style="font-size: 22px;"></i>正在加载设备信息...</div>
    <div class="countDevice">
      <el-card class="box-card">
        <div v-for="(item, index) in countDevice" :key="index" >
          <div class="countDevice-list" @click="selectStatus(index)" >
            <el-button  v-bind:type="item.iconcolor" icon="el-icon-star-off" circle size="mini"></el-button>
            <span class="name">{{item.name}}:</span>{{amount[index]}}</div>
        </div>
      </el-card>
    </div>
    <DeviceDetails
      :showdetails.sync="showdetails"
      :devicerow="devicerow"
      :driverow="driverow"
      :overspeedrow="overspeedrow"
      :driving="driving"
      :overspeed="overspeed"
      :warning="warning"
      :ChangeRecord="ChangeRecord"
      :loading="loading"
      v-on:changeModalPage="changeModalPage"
    ></DeviceDetails>
    <InportantWarning :showwarning.sync="showwarning" v-on:closeWarning="closeWarning" v-on:countImportant="countImportant"/>
  </div>
</template>
<script type="text/babel">
  import { trackList ,findTrackerPuzzy ,queryTrackerGroupList ,getDetails} from '@/api/map'
  import { countTracker} from '@/api/request'
  import {wgs84togcj02,gcj02tobd09, bd09togcj02,gcj02towgs84 ,formatTime} from '@/utils/index'
  import { Message } from 'element-ui'
  import Mainmap from '@/components/Mainmap'
  import InportantWarning from './importantwarning'
  import deviceDetails from '@/mixins/devicedetails'
  import DeviceDetails from '../devicetable/devicedetails'

  export default {
    name:'Allmap',
    mixins: [deviceDetails],
    data () {
      return {
        map:null,
        showwarning: true,
        list:[],
        seach:'',
        newList:[],
        listLoading:false,
        points:[],
        isShow:false,
        isJiejing:true,
        countDevice:[
          {
            name:'设备总数',
            iconcolor:'primary'
          },
          {
            name:'在线数量',
            iconcolor:'success'
          },
          {
            name:'离线数量',
            iconcolor:'warning'
          },
          {
            name:'休眠数量',
            iconcolor:'info'
          },
          {
            name:'报警数量',
            iconcolor:'danger'
          }
        ],
        markerClusterer:null,
        markers:[],
        warningUnhandledCount:0,
        amount:[0,0,0,0,0],
        ishowredwarning:false,
        zoom:12,
        maxLat:'',
        maxLng:'',
        minLat:'',
        minLng:'',
        centerlatlng:'',
        maploading:true,
        label:'',
        marker:'',
        drtimer:null,
        zmtimer:null,
        lotimer:null,
        markerdetails:{},
        issearch:false
      }
    },
    components: {
      Mainmap,
      InportantWarning,
      DeviceDetails
    },
    methods:{

      /***初始化坐标列表***/
      initmap(map) {
        let _this = this
        this.map = map
        map.setMinZoom(6)
        map.setMaxZoom(16)
        this.all() //设置当前城市
        this.countTtrackers()

        map.addEventListener('zoomend', function () {
          _this.zmtimer && clearTimeout(_this.zmtimer)
            _this.zmtimer = setTimeout(function () {
              if(!_this.issearch){
                _this.bounds()
              }
              _this.issearch=false
            }, 50)
        });

        map.addEventListener('moveend', function () {
          _this.lotimer && clearTimeout(_this.lotimer)
            _this.lotimer = setTimeout(function () {
              console.log(!_this.issearch,66)
              if(!_this.issearch){
                _this.bounds()
              }
              _this.issearch=false
            }, 50)
        });
      },

      /**@获取区域经纬度和当前的缩放等级**/
      bounds(){
        let bounds=this.map.getBounds(),
        sw=bounds.getSouthWest(),
        ne=bounds.getNorthEast()
        let pin1=bd09togcj02(ne.lng,ne.lat);
        let newPonit1=gcj02towgs84(pin1[0],pin1[1]);
        let pin2=bd09togcj02(sw.lng,sw.lat);
        let newPonit2=gcj02towgs84(pin2[0],pin2[1]);

        this.maxLng=newPonit1[0]
        this.maxLat=newPonit1[1]
        this.minLng=newPonit2[0]
        this.minLat=newPonit2[1]
        this.zoom=this.map.getZoom()
       this.requestlist({
         zoom:this.zoom,
         maxLng:this.maxLng,
         maxLat:this.maxLat,
         minLat:this.minLat,
         minLng:this.minLng
       })
      },

      /**@初始化请求**/
      requestlist(query){
        this.maploading = true
        queryTrackerGroupList(query).then( response => {
          if(response && response.body){
            this.list = response.body.lbsGroups||[];
            this.initgrop(this.list,0)
          }
          this.maploading = false
        })
      },

      /**@初始化所有设备**/
      initgrop(list,isview){
        let that=this
        let newList=[]
        let newPoints=[]
        if(list.length>0){
          for(var k=0;k<list.length;k++){
            if(list[k].lng && list[k].lng>0 && list[k].lat && list[k].lat>0){
              newList.push(list[k])
            }
          }
        }else {
          this.map.clearOverlays();
          Message({
            message: this.issearch?'没有查询到相关设备':'此范围内没有信息',
            type: 'error',
            duration: 2 * 1000
          })
        }

        if(newList.length>0){
          this.map.clearOverlays();
          for(let i=0;i<newList.length;i++){
              let pin=wgs84togcj02(newList[i].lng,newList[i].lat);
              let newPonit=gcj02tobd09(pin[0],pin[1]);
              if(isview===1){
                newPoints.push(new BMap.Point(newPonit[0],newPonit[1]))
              }
              if(newList[i].num>1){
                that.label = new BMap.Label(`<div class='lbsGroups'><div class='num'>${newList[i].num}</div></div>`, {
                  position:new BMap.Point(newPonit[0],newPonit[1]),
                  offset   : new BMap.Size(-25,-25)
                });
                that.label.setStyle({
                  color: "#fffefe",
                  borderWidth: "0",
                  padding: "0",
                  zIndex: "2",
                  backgroundColor: "transparent",
                  textAlign: "center"
                });
                this.map.addOverlay(that.label);
                that.label.addEventListener('click', function (e) {
                  if(that.zoom<=13){
                    that.map.centerAndZoom(new BMap.Point(newPonit[0],newPonit[1]),14)
                  }else {
                    that.label.hide()
                    that.map.centerAndZoom(new BMap.Point(newPonit[0],newPonit[1]),16)
                  }
                });
              }else {
                that.marker = new BMap.Marker(new BMap.Point(newPonit[0],newPonit[1]));
                that.marker.customData = { index: i };
                that.addClickHandler(that.marker);
                if(i==0 && isview==1 ){
                  let pin1=wgs84togcj02(newList[0].lng,newList[0].lat);
                  let newPonit1=gcj02tobd09(pin1[0],pin1[1]);
                  that.getmarker(newList[0].trackerId,new BMap.Point(newPonit1[0],newPonit1[1]),0);//默认打开第一个
                }
                that.map.addOverlay(that.marker);
              }
            }
           if(isview==1 && newPoints.length>0)  {
             that.issearch=true
             that.map.centerAndZoom(newPoints[0],that.zoom)
           }
           that.newList=newList
          }
      },

      /**@刷新所有设备**/
      refresh(){
        let _this=this
        _this.drtimer &&  clearTimeout(_this.drtimer)
        _this.drtimer = setTimeout(function () {
          _this.bounds()
        }, 50)
      },

      /**@查看所有设备**/
      all(){
        let _this=this
         /**本地开始**/
        function myFun(result) {
          let cityName = result.name;
          _this.map.setCenter(cityName);
        }
        let myCity = new BMap.LocalCity();
        myCity.get(myFun);
         /**本地结束**/

        /**永川开始**/
        // this.map.setCenter(new BMap.Point(105.917548,29.365948))
        // _this.drtimer &&  clearTimeout(_this.drtimer)
        // _this.drtimer = setTimeout(function () {
        //   _this.bounds()
        // }, 50)
        /**永川结束**/
      },

      /**@点击marker显示窗口信息**/
      addClickHandler(marker){
        let that=this;
        marker.addEventListener("click",function(e){
          let p = e.target;
          let point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
            that.getmarker(that.newList[e.target.customData.index].trackerId,point,e.target.customData.index)
        } );
      },

      getmarker(trackerId,point,index){
        let that=this;
        getDetails({trackerId:trackerId}).then( response => {
          if(response && response.body){
            this.markerdetails=response.body
          }

          that.getInfor(point,index,this.markerdetails);
        })
      },


      /**@创建窗口信息**/
      getInfor(point,index,newList) {
        let addr='';
        let that=this;
        let  geoc = new BMap.Geocoder();
        //窗口信息
        let opts = {
          width : 300,     // 信息窗口宽度
          height: 270,     // 信息窗口高度
          enableAutoPan:false,
          enableCloseOnClick:false
        };
        geoc.getLocation(point,function(rs){
          let trackstr= `{trackerId:${newList.trackerId},imei:'${newList.imei}'}`
          let followstr=`{trackerId:${newList.trackerId}}`
          let newTime='';
          if(newList.syncTime){
            newTime= formatTime(new Date(newList.syncTime))
          }

          if(rs){
            let addComp = rs.addressComponents;
            addr=(addComp.province  + addComp.city +  addComp.district +  addComp.street +  addComp.streetNumber);
          }
          let info= `
           <div class="infoContent">
              <p class="device_details device_details_title"><a href='javascript:;' onclick="openDetials(${index})">详情</a><a onclick="vista(${index})" href='javascript:;' >街景</a><a href='javascript:;' onclick="link(${followstr},1)">追踪</a><a href='javascript:;' onclick="link(${trackstr},2)">轨迹</a></p>
              <p class="device_details"><span class="device_title" >车牌号:</span><span>${newList.number||''}</span> </p>
              <p class="device_details"><span class="device_title">状态:</span><span>${newList.signalStatus==0?'离线':newList.signalStatus==1?'在线':'休眠'}</span> </p>
              <p class="device_details"><span  class="device_title">速度:</span><span>${newList.speed>0?parseInt(newList.speed):0}km/h</span> </p>
              <p class="device_details"><span class="device_title">通信信号:</span><span>${newList.rssi}</span> </p>
              <p class="device_details"><span class="device_title">GPS信号:</span><span>${newList.satellites}</span> </p>
              <p class="device_details"><span  class="device_title">经纬度:</span><span>${newList.lng},${newList.lat}</span></p>
              <p class="device_details"><span  class="device_title">位置:</span><span>${addr}</span></p>
              <p class="device_details"><span class="device_title">最后上传时间:</span><span>${newTime}</span></p>
              <p class="device_details"><span  class="device_title">IMEI号:</span><span>${newList.imei}</span></p>
              <p class="device_details"><span class="device_title">使用人:</span>${newList.userName||''}<span></span></p></div>`
          let InfoWindow=new BMap.InfoWindow(info,opts)
          that.map.openInfoWindow(InfoWindow,(point));
        });
      },

      /**@展示街景**/
      showJiejing(i){
        let fls = this.flashChecker();
        if(!fls.f) {
          window.location.href = "http://get.adobe.com/cn/flashplayer/";
        }else {
          let that=this;
          that.isShow=true;
          let pin=wgs84togcj02(that.newList[i].lng,that.newList[i].lat);
          let newPonit=gcj02tobd09(pin[0],pin[1]);
          let panoramaService = new BMap.PanoramaService();
          panoramaService.getPanoramaByLocation(new BMap.Point(newPonit[0],newPonit[1]), function(data){
            if (data == null) {
              that.isJiejing=false
            }else {
              that.isJiejing=true;
              let panorama = new BMap.Panorama('panorama');
              panorama.setPosition(new BMap.Point(newPonit[0],newPonit[1]));
            }
          });
        }
      },

      /***@检查是否支持flash*/
      flashChecker() {
        var hasFlash = 0;　　　　 //是否安装了flash
        var flashVersion = 0;　　 //flash版本

        if(document.all) {
          var swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
          if(swf) {
            hasFlash = 1;
            VSwf = swf.GetVariable("$version");
            flashVersion = parseInt(VSwf.split(" ")[1].split(",")[0]);
          }
        } else {
          if(navigator.plugins && navigator.plugins.length > 0) {
            var swf = navigator.plugins["Shockwave Flash"];
            if(swf) {
              hasFlash = 1;
              var words = swf.description.split(" ");
              for(var i = 0; i < words.length; ++i) {
                if(isNaN(parseInt(words[i]))) continue;
                flashVersion = parseInt(words[i]);
              }
            }
          }
        }
        return { f: hasFlash, v: flashVersion };
      },

      /**@关闭街景*/
      closeJiejing(){
        this.isShow=false;
      },

      /**@条件查询*/
      change(){
        let val=this.seach
        let that=this;
        if(val && val!==''){
          this.issearch=true
          that.listLoading = true;
          findTrackerPuzzy({condition:val}).then( response => {
            if(response.body){
              that.list = response.body;
            }else {
              that.list = [];
              Message({
                message: '没有此设备！',
                type: 'error',
                duration: 2 * 1000
              })
            }
            this.initgrop(that.list,1)
            that.listLoading = false
          })
        }else {
          this.all()
        }
      },

      /**@选择不同的状态**/
      selectStatus(i){
        let queryString={}
        if(i==1){
          queryString={
            signalStatus:1
          }
        }else if(i==2){
          queryString={
            signalStatus:0
          }
        }else if(i==3){
          queryString={
            signalStatus:2
          }
        }else if(i==4){
          queryString={
            status:1
          }
        }

        this.requestlist({
          zoom:this.zoom,
          maxLng:this.maxLng,
          maxLat:this.maxLat,
          minLat:this.minLat,
          minLng:this.minLng,
          ...queryString
        })
      },

      /**@统计设备**/
      countTtrackers(){
        let that=this;
        countTracker().then( response => {
          if(response && response.body){
            let count = response.body;
            that.amount=[count.totalCount,count.onlineCount,count.offlineCount,count.sleepCount,count.warningCount]
            that.warningUnhandledCount=count.warningUnhandledCount
          }
        })
      },

      openwarning(){
        this.showwarning = true
      },

      closeWarning(timer){
        this.showwarning = false
        clearTimeout(timer)
      },

      countImportant(list){
        if(list.length>0){
          this.ishowredwarning=true
          this.showwarning=true
        }else {
          this.ishowredwarning=false
          this.showwarning=false
        }
      }
    },
    mounted(){
      let that=this;
      window.vista=function(i){
        that.showJiejing(i)
      }
      window.openDetials=function (i) {
        that.showdetails=true
        that.trakerDetail(that.newList[i].trackerId,that.drivingquery)
      }

      window.link=function(query,id){
        if(id===1){
          that.$router.push({path: '/monitor/follow', query: query});
        }else {
          that.$router.push({path: '/monitor/track', query:query});
        }
      }
    },
    beforeDestroy(){
      clearTimeout(this.drtimer)
      clearTimeout(this.zmtimer)
      clearTimeout(this.lotimer)
    }
  }
</script>
